import {parse} from 'querystring';
import {history} from "@@/core/history";
import {REG_CODE} from "@/utils/constants";
import {message} from "antd";
import {Resp} from "@/services/api-types";

const reg = /(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/;

export const isUrl = (path: string): boolean => reg.test(path);

export const isAntDesignPro = (): boolean => {
  if (ANT_DESIGN_PRO_ONLY_DO_NOT_USE_IN_YOUR_PRODUCTION === 'site') {
    return true;
  }
  return window.location.hostname === 'preview.pro.ant.design';
};

// 给官方演示站点用，用于关闭真实开发环境不需要使用的特性
export const isAntDesignProOrDev = (): boolean => {
  const {NODE_ENV} = process.env;
  if (NODE_ENV === 'development') {
    return true;
  }
  return isAntDesignPro();
};

export const getPageQuery = () => parse(window.location.href.split('?')[1]);

export type SuccessResponse<T> = {
  code: 200
  message: string
  data: T
}
export type FailResponse = {
  code: number
  message: string
}
export type AsyncResponse<T = any> = Promise<Resp<T>>

export function isSuccessful<T>(response: Resp<T>): response is Resp<T> {
  return response.code == 200
}

export function isSuccess<T>(code: number): code is number {
  return code == 200
}

export const renderText = (text: any) => {
  return text ? text : '-'
}

export type ExtractFieldsOfType<Type, FieldType> = {
  [Key in keyof Type]: Type[Key] extends FieldType ? Key : never
}[keyof Type]

export const redirectIndex = () => {
  const urlParams = new URL(window.location.href);
  const params = getPageQuery();
  let {redirect} = params as { redirect: string };
  if (redirect) {
    const redirectUrlParams = new URL(redirect);
    if (redirectUrlParams.origin === urlParams.origin) {
      redirect = redirect.substr(urlParams.origin.length);
      if (redirect.match(/^\/.*#/)) {
        redirect = redirect.substr(redirect.indexOf('#') + 1);
      }
    } else {
      window.location.href = '/';
      return;
    }
  }
  history.replace(redirect || '/');
}

/**
 * 是否是手机号
 */
export const isCellphone = (str: string) => {
  return str && REG_CODE.CELLPHONE.test(str);
}

/**
 * 是否是邮箱
 */
export const isEmail = (str: string) => {
  return str && REG_CODE.EMAIL.test(str)
}

export const comingSoon = () => {
  message.warn('功能开发中，敬请期待...')
}

export const isEmpty = (object: any) => {
  if (object === null || object === undefined) return true
  if (typeof object === 'string') {
    if (object.trim() && object.trim().length > 0) return false
    return true
  }
  if (typeof object === 'object') {
    if (object.length > 0) return false
    return true
  }
  return false
}

// @ts-ignore
export const renderTreeNode = (node: { id: any, children: any[], name: string }) => {
  return {
    value: node.id,
    name: node.name,
    label: node.name,
    key: node.id,
    children: node.children.map(r => renderTreeNode(r))

  }
}

export const getBase64 = (file: any) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}

export const goto = (url: string) => {
  window.location.href = url
}

export const leftTime = (aimTime: string, showSeconds?: boolean) => {
  const aimDate=new Date(aimTime);  //开始时间
  const current = new Date();
  let left = aimDate.getTime() - current.getTime()  //时间差的毫秒数

  if (left < 0) {
    left = 0;
  }

  //计算出相差天数
  const days=Math.floor(left/(24*3600*1000))

  //计算出小时数

  const leave1=left%(24*3600*1000)    //计算天数后剩余的毫秒数
  const hours=Math.floor(leave1/(3600*1000))
  //计算相差分钟数
  const leave2=leave1%(3600*1000)        //计算小时数后剩余的毫秒数
  const minutes=Math.floor(leave2/(60*1000))


  //计算相差秒数
  const leave3=leave2%(60*1000)      //计算分钟数后剩余的毫秒数
  const seconds=Math.round(leave3/1000)


  return `${days}天${hours}小时${minutes}分钟${showSeconds?(seconds+'秒'):''}`;
}
